<template>
  <view class="address-book-container">
    <!-- 顶部标题 - 只在竖屏显示 -->
    <view class="header">
      <view class="terminal-selector" @tap="toggleCompanySelector">
        <text class="terminal-title">{{ selectedCompany.name }}</text>
        <uv-icon name="arrow-down" color="#333" size="20"></uv-icon>
      </view>
      <view class="add" @click="handleAdd">
        <uv-icon name="plus" size="15"></uv-icon>
      </view>
    </view>
    <!-- 搜索框 -->
    <view class="search-container">
      <uv-search :showAction="false" v-model="keyword" placeholder="input" shape="round"></uv-search>
      <!-- <view class="search-box">
					<image class="search-icon" src="/static/uniapp/search.png" mode=""></image>
				<input type="text" class="search-input" placeholder="input" v-model="searchText" />
			</view> -->
    </view>

    <!-- 联系人列表 -->
    <uv-index-list class="contact-lists" :index-list="[]" customNavHeight="100rpx">
      <view class="contact-list-item">
        <template v-for="(item, index) in itemArr">
          <uv-index-item>
            <!-- #ifndef APP-NVUE -->
            <view class="group-header">
              <text>Project Team {{ item.group }}</text>
            </view>
            <!-- #endif -->
            <view class="contact-item" v-show="showKewList(contact, keyword)" v-for="(contact, index) in item.users"
              :key="'team1-' + index" @click="handleItemClick(contact)">
              <image class="contact-avatar" :src="contact.avatar" mode="aspectFill"></image>
              <view class="contact-info">
                <text class="contact-name">{{ contact.nickname }}</text>
                <text class="contact-phone">{{ contact.phone }}</text>
              </view>
              <view class="itemBut">
                <view class="del-icon" @click.stop="hadleDel(contact)">
                  <uv-icon name="trash-fill" color="red" size="24"></uv-icon>
                </view>
                <view class="call-icon" @click.stop="callContact(contact)">
                  <image src="/static/uniapp/phone.png" mode=""></image>
                </view>
              </view>
            </view>
            <!-- <view class="list-cell" v-for="(cell, index) in item">
						item
					</view> -->
          </uv-index-item>
        </template>
      </view>
    </uv-index-list>
    <!-- 公司选择弹窗 -->
    <view class="company-selector-popup" v-if="showCompanySelector" @tap="showCompanySelector = false">
      <view class="company-selector-content" @tap.stop>
        <view class="company-selector-title">
          <text>选择公司</text>
        </view>

        <view class="company-list">
          <view class="company-item" @tap="selectCompany(item)" v-for="item in companyList" :key="item.id"
            :class="{ active: companyId === item.id }">
            <view class="radio-circle" :class="{ 'radio-selected': companyId === item.id }">
            </view>
            <text>{{ item.name }}</text>
          </view>
        </view>

        <view class="close-company-btn" @tap="showCompanySelector = false">
          <text>Close</text>
        </view>
      </view>
    </view>

    <uv-popup ref="showphoneModal" @change="changePopup" zIndex="999" round="20" :customStyle="{ overflow: 'initial' }">
      <view class="forgot-modal">
        <view class="modal-icon-box">
          <uv-icon class="modal-icon" size="56" color="#fff" name="lock-fill"></uv-icon>
        </view>
        <view class="modal-title">Submit Leave</view>
        <div class="form-conten">
          <uv-form :model="form" :labelWidth="120" :rules="rules" ref="form">
            <div class="form-top">
              <div class="formItems">
                <div class="lable">Reason</div>

                <view class="week-selector" style="margin:24rpx 0">
                  <view class="date-picker" @click="handleSelectList">
                    <image class="calendar-icon" src="/static/uniapp/duration.png" mode="aspectFit"></image>
                    <text class="selected-date">{{ form.department_name || 'Choose department' }}</text>
                    <image src="/static/uniapp/arrow-down.png" mode="" style="width: 40rpx; height: 40rpx"></image>
                  </view>
                </view>
              </div>
              <!-- <uv-form-item label="Reason" prop="username">
              </uv-form-item> -->
              <uv-form-item label="First name" prop="first_name">
                <uv-input border="none" v-model="form.first_name" placeholder="Please enter the First name" />
              </uv-form-item>
              <uv-form-item label="Last name" prop="last_name">
                <uv-input border="none" v-model="form.last_name" placeholder="Please enter the Last name" />
              </uv-form-item>
              <uv-form-item label="Category" prop="company_name">
                <uv-input border="none" v-model="form.company_name" placeholder="Please enter the Category" />
              </uv-form-item>
              <uv-form-item label="Title" prop="title">
                <uv-input v-model="form.title" border="none" placeholder="Please enter the Title" />
              </uv-form-item>
              <uv-form-item label="Email address" prop="email">
                <uv-input v-model="form.email" border="none" placeholder="Please enter the Email" />
              </uv-form-item>
              <uv-form-item label="Phone number" prop="phone">
                <uv-input v-model="form.phone" border="none" placeholder="Please enter the Phone" />
              </uv-form-item>
              <!-- <div class="formItem">
              <view class="form-title">Reason</view>

            </div> -->
            </div>
            <div class="form-bottom">
              <div class="formItem" v-for="item, index in phoneList" :key="index">
                <div class="itmeLeft" @click="reducePhone(index)">
                  <uv-icon name="minus-circle" size="20" color="red"></uv-icon>
                  <text>Cell phone</text>
                </div>
                <uv-input v-model="phoneList[index]" border="none" placeholder="Please enter the Phone" />
              </div>
              <div class="formItem">
                <div class="itmeLeft" @click="addPhone">
                  <uv-icon name="plus-circle-fill" size="20" color="#17A364"></uv-icon>
                  <text>Add phone</text>
                </div>
              </div>

            </div>
          </uv-form>
        </div>
        <div class="footBut">
          <button class="cancel-btn" @click="()=>{$refs.showphoneModal.close()}">Cancel</button>
          <button class="forgot-btn" @click="onSubmit(1)">Complete</button>
        </div>
      </view>
    </uv-popup>
    <uv-popup ref="showdelat" :zIndex="1001" round="20" :customStyle="{ overflow: 'initial' }">
      <view class="forgot-modal">
        <view class="modal-icon-box" style="background: red">
          <uv-icon class="modal-icon" size="56" color="#fff" name="trash"></uv-icon>
        </view>
        <view class="modal-title">Delete the contact!</view>
        <view class="modal-tip" style="text-align: left;">
          Are you sure you want to delete him/her? Once deleted, it will no longer appear in the list.
        </view>
        <button class="forgot-btn" style="margin-top: 30rpx;" @click="handleDel">Yes, delete him/her</button>
        <button class="cancel-btn" style="margin-top: 15rpx;" @click="$refs.showdelat.close()">No, return to the list</button>
      </view>
    </uv-popup>
    <uv-action-sheet :actions="departmentList" ref="showCodeModal" @select="select" @close="closeModal"
      :round="10"></uv-action-sheet>
  </view>
</template>

<script>
import { getaddressBook, getMyCompanyList, createUser, deleteUser, getDepartmentList } from "@/api/approval";
import { useCounterStore } from "@/store/counter";
import { mapActions } from "pinia";
export default {
  data() {
    return {
      companyId: "",
      keyword: "",
      selectedDate: {
        name: 'test'
      },
      selectedCompany: {},
      form: {
        first_name: '',
        nickname: '',
        avatar: '',
        category: '',
        last_name: '',
        title: '',
        company_id: '',
        phone: '',
        department_id: '',
        department_name: '',
      },
      showCompanySelector: false,
      searchText: "",
      currentLetter: "A",
      itemArr: [],
      companyList: [],
      phoneList: [''],
      departmentList: [],
      rules: {
        'form.first_name': {
          type: 'string',
          required: true,
          message: 'Please enter First name',
          trigger: ['blur', 'change']
        },
        'form.last_name': {
          type: 'string',
          max: 1,
          required: true,
          message: 'Please enter Last name',
          trigger: ['blur', 'change']
        },
        'form.title': {
          type: 'string',
          max: 1,
          required: true,
          message: 'Please enter Title',
          trigger: ['blur', 'change']
        },
        'form.email': {
          type: 'string',
          max: 1,
          required: true,
          message: 'Please enter Email address',
          trigger: ['blur', 'change']
        },
        'form.Category': {
          type: 'string',
          max: 1,
          required: true,
          message: 'Please enter Category',
          trigger: ['blur', 'change']
        },
        'form.phone': {
          type: 'string',
          max: 1,
          required: true,
          message: 'Please Phone number',
          trigger: ['blur', 'change']
        },
      },
    };
  },
  computed: {
    filteredContacts() {
      if (!this.searchText) {
        return [...this.teamOneContacts, ...this.teamTwoContacts];
      }

      const searchLower = this.searchText.toLowerCase();
      const filter = (contact) =>
        contact.name.toLowerCase().includes(searchLower) ||
        contact.phone.includes(this.searchText);

      return [
        ...this.teamOneContacts.filter(filter),
        ...this.teamTwoContacts.filter(filter),
      ];
    },
  },
  onShow() {
    this.getlist();
    getDepartmentList().then(res => {
      this.departmentList = res.map(ele => {
        this.form.department_id = ele.id
        this.form.department_name = ele.name
        return {
          ...ele,
          color: '#ffaa7f',
          fontSize: '20'
        }
      })
    })
  },
  methods: {
    ...mapActions(useCounterStore, ["setItem"]),
    addPhone() {
      this.phoneList.push('')
    },
    handleSelectList() {
      this.$refs.showCodeModal.open();
    },
    
		hadleDel(val) {
			this.$refs.showdelat.open('bottom');
      this.selectedDate = val
      console.log(this.selectedDate, 'selectedDate')
		},
    handleDel(){
      deleteUser(this.selectedDate.id).then(res => {
			  this.$refs.showdelat.close();
        uni.$uv.toast('Delete successfully')
        this.getlist();
      })
    },
    onSubmit() {
      this.$refs.form.validate().then(res => {
        let apiData = {
          ...this.form,
          dept_id: 1,
		  company_id:this.companyId,
          other_phone: this.phoneList||[]
        }
        createUser(apiData).then(res => {
          this.getlist();
          this.$refs.showphoneModal.close()
        })  
      }).catch(errors => {
        uni.showToast({
          icon: 'error',
          title: '校验失败'
        })
      })
    },
    select(val) {
      console.log('select', val)
      this.form.department_id = val.id
      this.form.department_name = val.name
    },
    reducePhone(index) {
      this.phoneList.splice(index, 1);
    },
    async getlist() {
      this.companyList = (await getMyCompanyList()) || [];
      if (this.companyList.length == 0) {
        return
      }
      this.selectedCompany = this.companyList[0];
      this.companyId = this.companyList[0].id;
      getaddressBook(this.companyId).then((res) => {
        console.log("getaddressBook", res);
        this.itemArr = res;
      });
    },
    showKewList(item, keyword) {
      if (!keyword) return true;
      return (
        item.nickname.toLowerCase().includes(keyword.toLowerCase()) ||
        item.phone.includes(keyword)
      );
    },
    handleAdd() {
      this.$refs.showphoneModal.open("bottom");
    },
    onScroll(e) {
      // 实际应用中，这里需要根据滚动位置更新当前字母
      // 这需要计算每个字母分区的位置
    },

    scrollToLetter(letter) {
      this.currentLetter = letter;
      // 实际应用中，这里应该滚动到对应字母的位置
      uni.showToast({
        title: `跳转到字母 ${letter}`,
        icon: "none",
      });
    },
    handleItemClick(contact) {
      this.setItem(contact);
      uni.navigateTo({
        url: `/pages/Contacts/detail?name=${contact.nickname}&id=${contact.id}&phone=${contact.phone}`,
      });
    },
    // 公司选择方法
    toggleCompanySelector() {
      console.log("Terminal selector clicked");
      this.showCompanySelector = !this.showCompanySelector;
    },
    selectCompany(company) {
      this.selectedCompany = company;
      this.companyId = company.id;
      this.showCompanySelector = false;
    },
    callContact(contact) {
      // event.stopPropagation();
      // uni.navigateTo({
      // 	url: `/pages/Contacts/detail?name=${contact.name}&phone=${contact.phone}`
      // });
      uni.showModal({
        title: "拨打电话",
        content: `确定要拨打 ${contact.nickname} 的电话 ${contact.phone} 吗？`,
        success: (res) => {
          if (res.confirm) {
            // 实际应用中，这里应该调用拨打电话的API
            uni.makePhoneCall({
              phoneNumber: contact.phone.replace(/\s/g, ""),
              fail: () => {
                uni.showToast({
                  title: "拨打电话失败",
                  icon: "none",
                });
              },
            });
          }
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  background-color: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
    Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.address-book-container {
  display: flex;
  flex-direction: column;
  position: relative;
  height: calc(100vh - 220rpx);
  /* 为底部导航留出空间 */
}

/* 搜索框 */
.search-container {
  padding: 0 30rpx 20rpx;
  background: #fff;
}

.contact-lists {
  padding: 15px;

  //margin-right: 10px;
  &::-webkit-scrollbar {
    display: none;
    /* Chrome, Safari */
  }

  .contact-list-item {
    background-color: #eaecf0;
    border-radius: 15px;
    border-bottom: 1px solid #eaecf0;
  }
}

.search-box {
  display: flex;
  align-items: center;
  height: 80rpx;
  border-radius: 40rpx;
  background-color: #f9fafb;
  padding: 0 30rpx;
}

.search-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
  opacity: 0.6;
}

.search-input {
  flex: 1;
  height: 80rpx;
  font-size: 30rpx;
  color: #333;
}

/* 联系人列表 */
.contact-list {
  flex: 1;
  height: calc(100vh - 290rpx);
  width: 86%;
  margin-left: 30rpx;
  margin-right: 30rpx;
}

.group-header {
  padding: 12rpx 24rpx;
  font-weight: 400;
  font-size: 15px;
  color: #475467;
  line-height: 23px;
  text-align: left;
}

.group-header-2 {
  position: relative;
  margin-top: 10rpx;
}

.group-marker {
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 8rpx;
  height: 40rpx;
  background-color: #19b36e;
  border-radius: 0 4rpx 4rpx 0;
}

.contact-item {
  display: flex;
  align-items: center;
  padding: 28rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #f0f0f0;
}

.contact-avatar {
  width: 96rpx;
  height: 96rpx;
  border-radius: 50%;
  margin-right: 24rpx;
}

.contact-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.contact-name {
  font-size: 15px;
  color: #101828;
  line-height: 23px;
  text-align: left;
  margin-bottom: 10rpx;
}

.contact-phone {
  font-size: 12px;
  color: #667085;
  line-height: 15px;
  text-align: left;
}

.itemBut {
  display: flex;
  justify-content: center;
  align-items: center;
}

.call-icon {
  width: 38rpx;
  height: 38rpx;
  margin-left: 10rpx;
}

.call-icon image {
  width: 38rpx;
  height: 38rpx;
}

/* 字母索引导航 */
.alphabet-nav {
  position: fixed;
  right: 10rpx;
  top: 50%;
  transform: translateY(-50%);
  display: flex;
  flex-direction: column;
  background-color: transparent;
  z-index: 999;
  background-color: #fff;
}

.letter-item {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #d0d5dd;
}

.letter-item.active {
  color: #19b36e;
  font-weight: 600;
}

/* 顶部标题样式 */
.header {
  padding-bottom: 30rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  justify-content: space-between;
  // border-bottom: 1px solid #eee;
}

.terminal-selector {
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  height: 84rpx;
}

.terminal-title {
  font-size: 38rpx;
  font-weight: 500;
  color: #333;
  margin-right: 10rpx;
}

/* 周选择器样式 */
.week-selector {
  margin: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  padding: 30rpx;
  border: 1px solid #eee;
}

.week-label {
  font-weight: 400;
  font-size: 12px;
  color: #475467;
  line-height: 15px;
  text-align: left;
  font-style: normal;
  text-transform: none;
  margin-right: 30rpx;
  font-weight: 400;
  display: flex;
  align-items: center;
  height: 50rpx;
  padding-right: 20rpx;
  margin-right: 20rpx;
  border-right: 1px solid #d0d5dd;
}

.line {
  font-size: 62rpx;
  color: #d0d5dd;
  font-weight: 300;
  line-height: 1;
  margin-left: 10rpx;
  display: inline-flex;
  align-items: center;
  transform: translateY(-4rpx);
}

.date-picker {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.calendar-icon {
  width: 38rpx;
  height: 38rpx;
  margin-right: 16rpx;
  color: #0e623d;
}

.selected-date {
  color: #333;
  flex: 1;
  font-weight: 400;
  font-size: 26rpx;
  color: #1d232e;
  line-height: 19px;
  text-align: left;
}

/* 公司选择弹窗样式 */
.company-selector-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: flex-end;
  /* 改为底部对齐 */
}

.company-selector-content {
  width: 100%;
  /* 宽度占满 */
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  /* 只保留顶部圆角 */
  padding: 30rpx;
  display: flex;
  flex-direction: column;
  animation: slideUp 0.3s ease;
  /* 添加向上滑动动画 */
}

.company-selector-title {
  font-size: 38rpx;
  color: #333;
  font-weight: 500;
  text-align: center;
  margin-bottom: 40rpx;
}

.company-list {
  margin-bottom: 40rpx;
}

.company-item {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1px solid #f0f0f0;
}

.radio-circle {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  border: 2rpx solid #e5e7eb;
  margin-right: 20rpx;
  background-color: #f9f9f9;
}

.radio-selected {
  border: 8rpx solid #17a364;
  background-color: #fff;
}

.company-item text {
  font-size: 34rpx;
  color: #333;
}

.close-company-btn {
  margin-top: 20rpx;
  height: 90rpx;
  border-radius: 100rpx;
  border: 1px solid #17a364;
  display: flex;
  justify-content: center;
  align-items: center;
}

.close-company-btn text {
  color: #17a364;
  font-size: 34rpx;
}

/* 横屏模式下的滚动条样式 */
.landscape-scroll {
  scroll-behavior: smooth;
  /* 使滚动更平滑 */
}

.footBut {
  display: flex;
  justify-content: space-around;
}

.form-conten {

  .form-top,
  .form-bottom {
    background: #F4F6F9;
    margin: 30rpx;
    padding: 30rpx;
    border-radius: 12px 12px 12px 12px;
  }

  .formItem {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    font-weight: 500;
    font-size: 22rpx;
    color: #4F5464;
    line-height: 19px;

    .itmeLeft {
      display: flex;
      align-items: center;

      .uv-icon {
        margin-right: 16rpx;
      }
    }
  }
}
</style>
